package com.ruoyi.system.controller;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Agenda;
import com.ruoyi.system.service.IAgendaService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import java.util.Date;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FileUtils;
import com.ruoyi.common.config.RuoYiConfig;
import java.io.File;

/**
 * 会议议程Controller
 * 
 * @author ruoyi
 * @date 2025-01-13
 */
@RestController
@RequestMapping("/system/agenda")
public class AgendaController extends BaseController
{
    @Autowired
    private IAgendaService agendaService;

    /**
     * 查询会议议程列表
     */
//    @PreAuthorize("@ss.hasPermi('system:agenda:list')")
    @GetMapping("/list")
    public TableDataInfo list(Agenda agenda)
    {
        startPage();
        List<Agenda> list = agendaService.selectAgendaList(agenda);
        return getDataTable(list);
    }

    /**
     * 导出会议议程列表
     */
//    @PreAuthorize("@ss.hasPermi('system:agenda:export')")
    @Log(title = "会议议程", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Agenda agenda)
    {
        List<Agenda> list = agendaService.selectAgendaList(agenda);
        ExcelUtil<Agenda> util = new ExcelUtil<Agenda>(Agenda.class);
        util.exportExcel(response, list, "会议议程数据");
    }

    /**
     * 获取会议议程详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:agenda:query')")
    @GetMapping(value = "/{agendaId}")
    public AjaxResult getInfo(@PathVariable("agendaId") Long agendaId)
    {
        return success(agendaService.selectAgendaByAgendaId(agendaId));
    }

    /**
     * 新增会议议程
     */
//    @PreAuthorize("@ss.hasPermi('system:agenda:add')")
    @Log(title = "会议议程", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Agenda agenda)
    {
        return toAjax(agendaService.insertAgenda(agenda));
    }

    /**
     * 修改会议议程
     */
//    @PreAuthorize("@ss.hasPermi('system:agenda:edit')")
    @Log(title = "会议议程", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Agenda agenda)
    {
        return toAjax(agendaService.updateAgenda(agenda));
    }

    /**
     * 删除会议议程
     */
//    @PreAuthorize("@ss.hasPermi('system:agenda:remove')")
    @Log(title = "会议议程", businessType = BusinessType.DELETE)
	@DeleteMapping("/{agendaIds}")
    public AjaxResult remove(@PathVariable Long[] agendaIds)
    {
        return toAjax(agendaService.deleteAgendaByAgendaIds(agendaIds));
    }

    /**
     * 根据会议ID查询议程啊列表
     */
    @GetMapping("/listByMeetId/{meetId}")
    public AjaxResult listByMeetId(@PathVariable("meetId") Long meetId) {
        List<Agenda> list = agendaService.selectAgendaByMeetId(meetId);
        return success(list);
    }

    /**
     * 批量新增会议议程
     */
    @PostMapping("/batchAdd")
    public AjaxResult batchAdd(@RequestBody Map<String, Object> params) {
        try {
            Long meetId = Long.parseLong(params.get("meetId").toString());
            List<Map<String, Object>> agendaList = (List<Map<String, Object>>) params.get("agendaList");
            
            List<Agenda> agendas = agendaList.stream().map(item -> {
                Agenda agenda = new Agenda();
                agenda.setMeetId(meetId);
                agenda.setAgendaTitle(item.get("agendaTitle") != null ? item.get("agendaTitle").toString() : null);
                agenda.setAgendaContent(item.get("agendaContent") != null ? item.get("agendaContent").toString() : null);
                agenda.setMinutesPath(item.get("minutesPath") != null ? item.get("minutesPath").toString() : null);
                if (item.get("startTime") != null) {
                    agenda.setStartTime(DateUtils.parseDate(item.get("startTime").toString()));
                }
                if (item.get("endTime") != null) {
                    agenda.setEndTime(DateUtils.parseDate(item.get("endTime").toString()));
                }
                return agenda;
            }).collect(Collectors.toList());
            
            return toAjax(agendaService.batchInsertAgenda(agendas));
        } catch (Exception e) {
            return AjaxResult.error("批量新增议程失败：" + e.getMessage());
        }
    }

    /**
     * 批量修改会议议程
     */
    @PostMapping("/batchUpdate")
    public AjaxResult batchUpdate(@RequestBody Map<String, Object> params) {
        try {
            Long meetId = Long.parseLong(params.get("meetId").toString());
            List<Map<String, Object>> agendaList = (List<Map<String, Object>>) params.get("agendaList");
            
            List<Agenda> agendas = agendaList.stream().map(item -> {
                Agenda agenda = new Agenda();
                agenda.setMeetId(meetId);
                agenda.setAgendaTitle(item.get("agendaTitle") != null ? item.get("agendaTitle").toString() : null);
                agenda.setAgendaContent(item.get("agendaContent") != null ? item.get("agendaContent").toString() : null);
                agenda.setMinutesPath(item.get("minutesPath") != null ? item.get("minutesPath").toString() : null);
                if (item.get("startTime") != null) {
                    agenda.setStartTime(DateUtils.parseDate(item.get("startTime").toString()));
                }
                if (item.get("endTime") != null) {
                    agenda.setEndTime(DateUtils.parseDate(item.get("endTime").toString()));
                }
                if (item.get("agendaId") != null) {
                    agenda.setAgendaId(Long.parseLong(item.get("agendaId").toString()));
                }
                return agenda;
            }).collect(Collectors.toList());
            
            return toAjax(agendaService.batchUpdateAgenda(agendas));
        } catch (Exception e) {
            return AjaxResult.error("批量修改议程失败：" + e.getMessage());
        }
    }

    /**
     * 上传会议纪要
     */
    @PostMapping("/uploadMinutes/{agendaId}")
    public AjaxResult uploadMinutes(@PathVariable Long agendaId, @RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件不能为空");
            }
            
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            // 生成新的文件名
            String fileName = DateUtils.datePath() + "/" + System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
            
            // 上传文件
            String filePath = RuoYiConfig.getUploadPath() + "/minutes/" + fileName;
            File dest = new File(filePath);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
            
            // 更新议程的会议纪要路径
            Agenda agenda = new Agenda();
            agenda.setAgendaId(agendaId);
            agenda.setMinutesPath(fileName);
            agendaService.updateAgenda(agenda);
            
            return AjaxResult.success("上传成功", fileName);
        } catch (Exception e) {
            return AjaxResult.error("上传会议纪要失败：" + e.getMessage());
        }
    }
}
